#!/usr/bin/python
# coding:utf-8

import os
import sys
import json
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QFileDialog, QTextEdit, QComboBox, QHBoxLayout, QVBoxLayout
from PyQt6.QtGui import QGuiApplication

from main import Translation
from utils import start_file
from settings import LANGUAGE
from language import LNG

lng = LNG[LANGUAGE]


class Window(QWidget):

    def __init__(self):
        super().__init__()

        self.str_in_dir = ''
        self.str_out_dir = ''
        self.instance = None
        # self.initUi()
        self.readHistroy()

    def initUi(self):
        v_lay_1 = QVBoxLayout()
        h_lay_1 = QHBoxLayout()
        h_lay_2 = QHBoxLayout()
        h_lay_3 = QHBoxLayout()
        h_lay_4 = QHBoxLayout()

        # 输入文本框
        # self.label_in_dir = QLineEdit(self)
        # self.label_in_dir.setText(lng[1])
        # self.label_in_dir.setReadOnly(True)
        # 输入目录历史记录
        self.in_combo = QComboBox(self)
        if 'in' in self.history and len(self.history['in']) > 0:
            self.str_in_dir = self.history["in"][0]
            for item in self.history["in"]:
                self.in_combo.addItem(item)
        else:
            self.in_combo.addItem(lng[1])
            pass
        self.in_combo.activated.connect(self.handleInEvent)
        # 选择输入目录
        in_btn = QPushButton(lng[2], self)
        in_btn.clicked.connect(self.handleInDialog)
        in_btn.setStyleSheet('''
            height:30px;
            font: bold 14px;
        ''')

        # 输出文本框
        # self.label_out_dir = QLineEdit(self)
        # self.label_out_dir.setText('请选择json目录！')
        # self.label_out_dir.setReadOnly(True)
        # 输出目录历史记录
        self.out_combo = QComboBox(self)
        if 'out' in self.history and len(self.history['out']) > 0:
            self.str_out_dir = self.history["out"][0]
            for item in self.history["out"]:
                self.out_combo.addItem(item)
        else:
            self.out_combo.addItem(lng[3])
            pass
        self.out_combo.activated.connect(self.handleOutEvent)

        # 下载信息提示区域
        self.text_edit = QTextEdit('', self)
        self.text_edit.setReadOnly(True)

        # 选择输出目录按钮
        out_btn = QPushButton(lng[4], self)
        out_btn.clicked.connect(self.handleOutDialog)
        out_btn.setStyleSheet('''
            height:30px;
            font: bold 14px;
        ''')

        # 打开目录
        opendir_btn = QPushButton(lng[5])
        opendir_btn.clicked.connect(self.openDirEvent)
        opendir_btn.setStyleSheet('''
            height:30px;
            font: bold 14px;
        ''')
        # 提交按钮
        submit_btn = QPushButton(lng[6], self)
        submit_btn.clicked.connect(self.handleEvent)
        submit_btn.setStyleSheet('''
            height:30px;
            font: bold 14px;
        ''')

        # h_lay_1.addWidget(self.label_in_dir)
        h_lay_1.addWidget(self.in_combo)
        h_lay_1.addWidget(in_btn)
        # h_lay_2.addWidget(self.label_out_dir)
        h_lay_2.addWidget(self.out_combo)
        h_lay_2.addWidget(out_btn)
        h_lay_3.addStretch(1)
        h_lay_3.addWidget(opendir_btn)
        h_lay_3.addWidget(submit_btn)
        h_lay_4.addWidget(self.text_edit)

        v_lay_1.addLayout(h_lay_1)
        v_lay_1.addLayout(h_lay_2)
        v_lay_1.addLayout(h_lay_3)
        v_lay_1.addLayout(h_lay_4)

        self.setLayout(v_lay_1)

        # 主框体设置
        self.resize(300, 380)
        self.setFixedSize(self.width(), self.height())
        self.setWindowTitle(lng[7])
        self.center()
        self.show()

    # 内容居中
    def center(self):
        frame = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        frame.moveCenter(cp)
        self.move(frame.topLeft())

    # 提交后判断逻辑
    def handleEvent(self, event):
        if self.str_in_dir == '' or self.str_in_dir == lng[1]:
            replay = QMessageBox.warning(self, lng[8], lng[1], QMessageBox.Yes)
            if replay == QMessageBox.Yes:
                self.handleInDialog()
        elif self.str_out_dir == '' or self.str_out_dir == lng[3]:
            replay = QMessageBox.warning(self, lng[8], lng[3], QMessageBox.Yes)
            if replay == QMessageBox.Yes:
                self.handleOutDialog()
        else:
            if self.instance is None:
                self.instance = Translation(self.str_in_dir, self.str_out_dir)
                self.instance.newText.connect(self.showPrint)
            else:
                self.instance.init_data(self.str_in_dir, self.str_out_dir)
            self.instance.get_excels()

            # 将历史记录写入缓存文件
            self.writeHistroy()
        pass

    # 处理输入下拉框方法
    def handleInEvent(self, event):
        """
        处理输入下拉框方法
        """
        if event == lng[10]:
            self.str_in_dir = ''
            self.history['in'] = []
            self.initCombobox('in')
            self.writeHistroy()
        else:
            self.str_in_dir = event

    def handleOutEvent(self, event):
        """
        处理输出下拉框方法
        """
        if event == lng[10]:
            self.str_out_dir = ''
            self.history['out'] = []
            self.initCombobox('out')
            self.writeHistroy()
        else:
            self.str_out_dir = event

    # 处理点击打开目录按钮的方法
    def openDirEvent(self):
        if self.str_out_dir == '' or self.str_out_dir == lng[3]:
            replay = QMessageBox.warning(self, lng[8], lng[3], QMessageBox.Yes)
            if replay == QMessageBox.Yes:
                self.handleOutDialog()
        else:
            start_file(self.str_out_dir)

    # 通过信号与槽技术传输打印信息
    def showPrint(self, value):
        self.text_edit.append(value)
        # print('f====={0}'.format(value))

    def handleInDialog(self):
        """
        处理输入目录数据
        """
        dir_path = QFileDialog.getExistingDirectory(self, lng[1], '')
        if dir_path == '':
            return
        self.str_in_dir = dir_path
        # self.label_in_dir.setText(dir_path)
        self.check_combo('in', dir_path)

    # 处理输出目录数据
    def handleOutDialog(self):
        dir_path = QFileDialog.getExistingDirectory(self, lng[3], '')
        if dir_path == '':
            return
        self.str_out_dir = dir_path
        # self.label_out_dir.setText(dir_path)
        self.check_combo('out', dir_path)
        pass

    def check_combo(self, htype, dir_path):
        """
        检查是否需要更新历史记录和combox组件
        """
        if htype == 'in':
            widget = self.in_combo
        else:
            widget = self.out_combo
        # 如果数组不存在，则新建数组
        if htype not in self.history:
            self.history[htype] = [dir_path, lng[10]]
        else:
            # 如果“清除历史记录”不在数组中，则加入
            if lng[10] not in self.history[htype]:
                self.history[htype].append(lng[10])
            # 如果路径不在数组中，则加入数组首部
            if dir_path not in self.history[htype]:
                self.history[htype].insert(0, dir_path)
            pass
        widget.clear()
        widget.addItems(self.history[htype])
        pass

    def readHistroy(self):
        """
        读取缓存文件的历史数据
        """
        file = os.path.join(os.getcwd(), 'data.json')
        if os.path.isfile(file):
            with open(file, 'r', encoding='utf-8') as f:
                self.history = json.load(f)
                self.initUi()
        else:
            self.history = {}
            self.initUi()
        pass

    def writeHistroy(self):
        """
        写入缓存文件
        """
        file = os.path.join(os.getcwd(), 'data.json')
        with open(file, 'w', encoding='utf-8') as f:
            json.dump(self.history, f)
            pass

    def initCombobox(self, htype):
        """
        Combobox增加默认配置项
        """
        if htype == 'in':
            self.in_combo.clear()
            self.in_combo.addItem(lng[1])
        else:
            self.out_combo.clear()
            self.out_combo.addItem(lng[3])


def main():
    app = QApplication(sys.argv)
    window = Window()  # 必须赋值给一个变量，才能出现程序界面
    sys.exit(app.exec())


main()
# if __name__ == "__main__":
#     main()
